package fractal.filter;

public class EqualizeFilter extends FractalFilter
{
	private int[][] lut;

	public EqualizeFilter()
	{
	}

	@Override
	protected void initFilter()
	{
		Histogram histogram = new Histogram(inPixels, width, height, 0, width);
		if (histogram.getNumSamples() > 0)
		{
			int i, j;
			float scale = 255.0f / histogram.getNumSamples();
			lut = new int[3][256];
			for (i = 0; i < 3; i++)
			{
				lut[i][0] = histogram.getFrequency(i, 0);
				for (j = 1; j < 256; j++)
					lut[i][j] = lut[i][j - 1] + histogram.getFrequency(i, j);
				for (j = 0; j < 256; j++)
					lut[i][j] = Math.round(lut[i][j] * scale);
			}
		} else
			lut = null;
	}

	@Override
	protected int calculatePixel(int i)
	{
		int rgb = inPixels[i];
		if (lut != null)
		{
			int a = rgb & 0xff000000;
			int r = lut[Histogram.RED][(rgb >> 16) & 0xff];
			int g = lut[Histogram.GREEN][(rgb >> 8) & 0xff];
			int b = lut[Histogram.BLUE][rgb & 0xff];
			return a | (r << 16) | (g << 8) | b;
		}
		return rgb;
	}
}
